<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import type { TreeData, TreeInstance } from 'element-plus';
import { fetchGetDeptTree } from '@/service/api';

defineOptions({ name: 'DeptTreeSelect' });

const props = defineProps<{
  disabledId?: CommonType.IdType;
  // 当前 ID 及所有子节点禁用
  disabledChilrenId?: CommonType.IdType;
}>();

const treeSelectRef = ref<TreeInstance | null>(null);
const treeData = ref<TreeData>([]);

onMounted(async () => {
  const { data, error } = await fetchGetDeptTree();
  if (!error && data) {
    if (props.disabledId || props.disabledChilrenId) {
      nodeDisabled(data.children || []);
    }
    treeData.value.push(data);
  }
});

/** 判断节点是否禁用 */
function nodeDisabled(nodes: any, disabled: boolean = false) {
  nodes.forEach((item: any) => {
    if (props.disabledId) {
      item.disabled = item.value.toString() === props.disabledId.toString();
      nodeDisabled(item.children);
    } else if (props.disabledChilrenId) {
      item.disabled = item.value === props.disabledChilrenId.toString() || disabled;
      if (item.children && item.children.length > 0) {
        nodeDisabled(item.children, item.disabled);
      }
    }
  });
}

const model = defineModel<CommonType.IdType>('modelValue', {
  default: 0
});

watch(
  () => props.disabledChilrenId,
  () => {
    nodeDisabled(treeData.value || []);
  }
);
</script>

<template>
  <ElTreeSelect
    v-if="treeData && treeData.length > 0"
    ref="treeSelectRef"
    v-model="model"
    :data="treeData"
    node-key="value"
    :empty-values="['']"
    value-on-clear=""
    show-checkbox
    check-strictly
    check-on-click-node
    clearable
  />
</template>

<style scoped lang="scss"></style>
